// Package api internal/api/auth_api.go
package api

import (
	"gozrd-admin-api/internal/entity/dto"
	"gozrd-admin-api/internal/repository"
	"gozrd-admin-api/internal/service"
	rediscaptchastore "gozrd-admin-api/pkg/redis-captcha-store"
	"gozrd-admin-api/pkg/response"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
)

// AuthAPI 认证控制器
type AuthAPI struct {
	captchaService service.ICaptchaService
	loginService   service.ILoginService
}

// NewAuthAPI 创建认证控制器
func NewAuthAPI(redisClient *redis.Client, db *gorm.DB, expiration time.Duration) AuthAPI {
	store := rediscaptchastore.NewRedisCaptchaStore(redisClient, expiration)
	captchaService := service.NewCaptchaService(store)

	adminRepo := repository.NewAdminRepository(db)
	menuRepository := repository.NewMenuRepository(db)
	loginInfoRepository := repository.NewLoginInfoRepository(db)
	loginService := service.NewLoginService(adminRepo, menuRepository, loginInfoRepository, store)

	return AuthAPI{
		captchaService: captchaService,
		loginService:   loginService,
	}
}

// GetCaptcha 获取验证码
// @Summary 获取验证码
// @Description 获取图形验证码
// @Tags 认证
// @Accept json
// @Produce json
// @Success 200 {object} response.Response{data=vo.CaptchaVo} "成功"
// @Router /auth/captcha [get]
func (a AuthAPI) GetCaptcha(c *gin.Context) {
	a.captchaService.GetCaptcha(c)
}

// Login 用户登录接口
// @Summary 用户登录接口
// @Produce json
// @Description 用户登录接口
// @Tags 认证
// @Param data body dto.LoginDto true "data"
// @Success 200 {object} response.Response "ok"
// @Router /auth/login [post]
func (a AuthAPI) Login(c *gin.Context) {
	var loginDTO dto.LoginDto
	if err := c.ShouldBindJSON(&loginDTO); err != nil {
		response.Fail(c, response.ErrParams, err.Error())
		return
	}

	a.loginService.Login(c, loginDTO)
}

// SetServicesForTest 设置服务，仅供测试使用
func SetServicesForTest(a *AuthAPI, captchaSvc service.ICaptchaService, loginSvc service.ILoginService) {
	a.captchaService = captchaSvc
	a.loginService = loginSvc
}
